package sql

import (
	"database/sql/driver"
	"fmt"
	"time"
)

var zeroTime time.Time

type DateTime struct {
	time.Time
}

// MarshalJSON on DateTime format Time field with %Y-%m-%d %H:%M:%S
func (t DateTime) MarshalJSON() ([]byte, error) {
	if t.UnixNano() == zeroTime.UnixNano() {
		return []byte("null"), nil
	} else {
		formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
		return []byte(formatted), nil
	}
}

// Value insert timestamp into mysql need this function.
func (t DateTime) Value() (driver.Value, error) {
	if t.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan valueof DateTime time.Time
func (t *DateTime) Scan(v interface{}) error {
	switch v.(type) {
	case []byte:
		timeBytes, ok := v.([]byte)
		if ok {
			value, _ := time.ParseInLocation("2006-01-02 15:04:05", string(timeBytes), time.Local)
			*t = DateTime{Time: value}
			return nil
		}
	case time.Time:
		value, ok := v.(time.Time)
		if ok {
			*t = DateTime{Time: value}
			return nil
		}

	}
	return fmt.Errorf("can not convert %v to DateTime", v)
}
